package com.filldream.sun.openapi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.filldream.sun.bean.express.JuHeExpress;
import com.filldream.sun.bean.express.JuHeExpressList;
import com.filldream.sun.core.JsonUtil;
import com.filldream.sun.core.UrlUtil;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class JuHeExpUtil {

    /**
     * 获取聚合快递信息
     * @param com   快递公司编号
     * @param no    快递单号
     * @param key   聚合key
     * @return
     * @throws IOException
     */
    public static JuHeExpress getExpList(String com,String no,String key) throws IOException {
        JuHeExpress result = new JuHeExpress();
        String url = "http://v.juhe.cn/exp/index?com=" + com + "&no=" + no + "&dtype=json&key=" + key;;
        String juheJson = UrlUtil.doGet(url);

        JSONObject jsonObject = JSONObject.parseObject(juheJson);
        result.setErrorCode(jsonObject.getInteger("error_code"));
        result.setReason(jsonObject.getString("reason"));
        Map<String, Object> map = (Map<String, Object>) jsonObject.get("result");

        result.setCom(com);
        result.setNo(no);
        result.setExpressList(Collections.<JuHeExpressList>emptyList());

        if(map != null && !map.isEmpty()){
            result.setCompany((String)map.get("company"));
            result.setCom((String)map.get("com"));
            result.setNo((String)map.get("no"));
            result.setStatus((String)map.get("status"));
            result.setStatusDetail((String)map.get("status_detail"));
            JSONArray list = (JSONArray)map.get("list");
            List<JuHeExpressList> juHeExpressLists = JsonUtil.fromJosnArray(list.toJSONString(), JuHeExpressList.class);
            if(!juHeExpressLists.isEmpty()){
                result.setExpressList(juHeExpressLists);
            }
        }
        return result;
    }

}
